package com.hzqy.web.ac;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hzqy.commons.utils.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.hzqy.commons.utils.FileType;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.service.picture.PictureServiceBean;
import com.hzqy.web.vo.CmPicturesRelationVo;
import com.hzqy.web.vo.CmPicturesVo;

import static com.hzqy.commons.utils.FileUtil.fileCheck;

@Controller
@RequestMapping("/")
public class PictureAction {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	
	private static final String[] allowedFileType = new String[]{"png", "jpg", "gif","zip","jar","tar"};
	
	@Resource
	private PictureServiceBean pictureServiceBean;
	
	@RequestMapping("/picture/pictureRelationSelect")
	@ResponseBody
	public Object pictureRelationSelect(String picType) {
		List<CmPicturesRelationVo> list = pictureServiceBean.picturesRelationSelectList(picType);
		return list;
	}
	
	@RequestMapping("/picture/upPictures")
	@ResponseBody
	public Object upPicture(HttpServletRequest request ,HttpServletResponse response,HttpSession session) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = null;
		int flag = -1;
		String picLeftFile = session.getServletContext().getInitParameter("img_path");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadify");
		String uploadifyFileName = file.getOriginalFilename();
		String fileType = request.getParameter("fileType");
		InputStream is = null;
		try{
			is = file.getFileItem().getInputStream();
			if((FileType.checkFileType(file.getFileItem().getInputStream(), allowedFileType) && FileUtils.checkExtendNameByPicture(uploadifyFileName))||"all".equals(fileType)) {
				if(checkImageFileSize(file)) {

					String picType = request.getParameter("picType");
					picType = URLDecoder.decode(picType, "UTF-8");
					String filePath = pictureServiceBean.getFilePath(picType);
					String fileName = pictureServiceBean.getFileName(uploadifyFileName);

					if(fileCheck(picLeftFile + filePath,fileName)){
						File picFile = new File(picLeftFile + filePath,fileName);
						if(!picFile.exists())
							picFile.mkdirs();
						try {
							file.transferTo(picFile);
						} catch(Exception e) {
							LOG.error("上传图片异常：",e);
						}
						result = filePath+fileName;
						flag = 1;
						resultMap.put("result", result);
					}else {
						result="上传文件方式异常";
					}

				} else {
					result = "文件尺寸过大 " + uploadifyFileName + " 文件尺寸: " + file.getSize() + "b";
				}
			} else {
				result = "上传图片异常：文件类型不支持: " + uploadifyFileName;
			}
			response.setContentType("text/html;charset=UTF-8");
		}catch (Exception e){

		}finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}


		/*try {
			PrintWriter out = response.getWriter();
			out.write(result);
			out.close();
		} catch (IOException e) {
			LOG.error("上传图片-回复图片路径异常：",e);
		}*/


		
		resultMap.put("flag", flag);
		resultMap.put("msg", result);
		return resultMap;
	}
	
	private boolean checkImageFileSize(CommonsMultipartFile file) {
		String maxImageFileSizeStr = SystemConfigUtils.getSysConfig("sys_upload_img_max_file_size");
		if(StringUtils.isNotEmpty(maxImageFileSizeStr)) {
			long maxImageFileSize = Long.valueOf(maxImageFileSizeStr);
			if(file.getSize() > maxImageFileSize) {
				return false;
			}
		}
		
		return true;
	}
	
	@RequestMapping("/picture/selectPictureList")
	@ResponseBody
	public Object selectPictureList(int f_cp_relationid,String picType,HttpSession session) {
		Map<String,String> map = new HashMap<String, String>();
		map.put("picType", picType);
		map.put("f_cp_relationid", String.valueOf(f_cp_relationid));
		List<CmPicturesVo> list = pictureServiceBean.selectPictureList(map);
		Map resultMap = new HashMap();
		resultMap.put("imgPath", session.getServletContext().getInitParameter("img_url"));
		resultMap.put("list", list);
		return resultMap;
	}
}
